package org.jdesktop.swingx.table.model;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.TableModel;

public abstract class AbstractCompositionTableModelWapper extends  AbstractTableModelWapper<TableModel> {

	protected ArrayList<AbstractTableModelWapper> subModel;
	protected int[] subRowCount;

	public AbstractCompositionTableModelWapper(TableModel t) {
		super(t);
		subModel=new ArrayList<AbstractTableModelWapper>();
		analysis(t,subModel);
		reResetValues();
	}

	public abstract void analysis(TableModel base,ArrayList<AbstractTableModelWapper> subModel);
	
	
	protected void reResetValues(){
		subRowCount=new int[subModel.size()];
		for(int i=0;i<subModel.size();i++)
			subRowCount[i]=subModel.get(i).getRowCount();
	}
				
	@Override
	public int getRowCount() {
		int rowCount=0;
		for(int i=0;i<subRowCount.length;i++)
			rowCount+=subRowCount[i];
		return rowCount;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		return getSectionTableModel(rowIndex).getValueAt(getSesctionTableModelRowIndex(rowIndex), columnIndex);
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return getSectionTableModel(rowIndex).isCellEditable(getSesctionTableModelRowIndex(rowIndex), columnIndex);
	}

	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		getSectionTableModel(rowIndex).setValueAt(aValue,getSesctionTableModelRowIndex(rowIndex),columnIndex);
	}

	@Override
	public int getRealRowNumber(int wapperRowNum) {
		return getSectionTableModel(wapperRowNum).getRealRowNumber(getSesctionTableModelRowIndex(wapperRowNum));
	}

	protected int getSesctionTableModelRowIndex(int wapperRowIndex){
		for(int i=subRowCount.length-1;i>=0;i--){
			if(subRowCount[i]>=wapperRowIndex)
				return wapperRowIndex-subRowCount[i];
		}
		return 0;
	}
	
	protected AbstractTableModelWapper getSectionTableModel(int wapperRowIndex){
		for(int i=subRowCount.length-1;i>=0;i--)
			if(subRowCount[i]>=wapperRowIndex)
				return subModel.get(i);
		return null;
	}
	
	
	//nosuped this model;
	@Override
	public int getRowIndex(int wapperRowIndex) {
		return -1;
	}

	@Override
	public int getColumnIndex(int wapperColumnIndex) {
		// TODO Auto-generated method stub
		return -1;
	}
	
}
